/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of GW-Android.

GW-Android is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

GW-Android is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with GW-Android. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.gw.android;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/*
 * Adaptado da aplicação exemplo do Android Notepad.
 */
public class ServersDbAdapter {
	public static final String LOG_TAG = "ServersDbAdapter";
	
	public static final String KEY_NAME = "name";
    public static final String KEY_URL = "url";
    public static final String KEY_ROWID = "_id";

    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    
    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
    		"create table servers (_id integer primary key autoincrement, "
    		+ "name text not null, url text not null);";

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "servers";
    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {
    	DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(LOG_TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS servers");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public ServersDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public ServersDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        
        return this;
    }
    
    public void close() {
        mDbHelper.close();
    }

    /**
     * Create a new server using the name and url provided. If the server is
     * successfully created return the new rowId for that server, otherwise
     * return a -1 to indicate failure.
     * 
     * @param name o nome do servidor
     * @param url a url do servidor
     * @return rowId or -1 if failed
     */
    public long createServer(String name, String url) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_URL, url);

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Delete the server with the given rowId
     * 
     * @param rowId id do servidor a ser removido
     * @return true if deleted, false otherwise
     */
    public boolean deleteServer(long rowId) {
        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all servers in the database
     * 
     * @return Cursor over all notes
     */
    public Cursor fetchAllServers() {
        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
                KEY_URL}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the server that matches the given rowId
     * 
     * @param rowId id do servidor
     * @return Cursor positioned to matching server, if found
     * @throws SQLException if server could not be found/retrieved
     */
    public Cursor fetchServer(long rowId) throws SQLException {
        Cursor mCursor =
                mDb.query(true, DATABASE_TABLE, new String[] { KEY_ROWID,
                        KEY_NAME, KEY_URL }, KEY_ROWID + "=" + rowId, null,
                        null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    /**
     * Update the server using the details provided. The server to be updated is
     * specified using the rowId, and it is altered to use the name and url
     * values passed in
     * 
     * @param rowId id of server to update
     * @param name value to set server name to
     * @param url value to set server url to
     * @return true if the server was successfully updated, false otherwise
     */
    public boolean updateServer(long rowId, String title, String body) {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, title);
        args.put(KEY_URL, body);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}